#include "FASqlite/YKSqlite.h"
#include "FASqlite/sqlite3.h"
#ifdef WIN32
#include <windows.h>
#else
#include <string>
#endif

#define MAX_PATH 256

CYKSqlite * gYKSqlite = NULL;

void MbcsToUtf8(const char *file,char *szBufOut,int nOutSize)
{
#ifdef WIN32
	wchar_t   *pwchar=0;
	int len=0;
	int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
	len=MultiByteToWideChar(codepage, 0, file, -1, NULL,0);
	pwchar=new wchar_t[len];
	if(pwchar!=0)
	{
		len = MultiByteToWideChar(codepage, 0, file, -1, pwchar, len);
		if( len!=0 ) 
		{
			len = WideCharToMultiByte(CP_UTF8, 0, pwchar, -1, szBufOut, nOutSize,0, 0);	 	
		}
		delete pwchar; 
	}
#else
	sprintf(szBufOut,"%s",file);
#endif
}

CYKSqlite::CYKSqlite(void)
{
	m_pDatabase=NULL;
	m_pLastError=NULL;
	m_nLastErrorCode=SQLITE_OK;
}

CYKSqlite::~CYKSqlite(void)
{
	Close();
}

bool   CYKSqlite::Open(char* lpszFileName,int nFlag)
{
	if(!lpszFileName)
		return false;

	if(m_pDatabase)
		Close();

	int nOpenFlag = 0;
	if(nFlag&READ_ONLY)
		nOpenFlag |= SQLITE_OPEN_READONLY;
	if(nFlag&READ_WRITE)
		nOpenFlag |= SQLITE_OPEN_READWRITE;
	if(nFlag&CREATE)
		nOpenFlag |= SQLITE_OPEN_CREATE;

	char szFile[MAX_PATH]={0};

	MbcsToUtf8(lpszFileName,szFile,sizeof(szFile));

	m_nLastErrorCode= sqlite3_open_v2(szFile,&m_pDatabase,nOpenFlag,NULL);
	
	if(m_nLastErrorCode!=SQLITE_OK)
	{
		return false;
	}	
	
	if(m_pDatabase==NULL)
		return false;
	return true;
}
bool   CYKSqlite::IsOpen()
{
	return m_pDatabase!=NULL;

}
bool   CYKSqlite::Close()
{
	if(m_pDatabase)
	{
		sqlite3_close(m_pDatabase);
		m_pDatabase=NULL;
		m_pLastError=NULL;
		return true;
	}
	return false;
}
bool   CYKSqlite::Execute(char* lpszSQL, YKSQLITE_CALLBACK pCallback, void *pUnuse, int &nErrCode)
{
	if(m_pDatabase)
	{
		m_nLastErrorCode=sqlite3_exec(m_pDatabase,lpszSQL,pCallback,pUnuse,&m_pLastError);
		return SQLITE_OK==m_nLastErrorCode;
	}
	return false;
}
char* CYKSqlite::GetLastError()
{
	return m_pLastError?m_pLastError:0;
}

//////////////////////////////////////////////////////////////////////////

extern "C" {
	FA_API ISqlite* CreateObject(ISqliteHandle *p)
	{
		if (gYKSqlite == NULL)
		{
			gYKSqlite = new CYKSqlite();
		}

		return gYKSqlite;
	}
	FA_API void ReleaseObject()
	{
		if (gYKSqlite)
		{
			delete gYKSqlite;
			gYKSqlite = NULL;
		}
	}
}